import React, { useState, useEffect } from 'react';
import {
  Table,
  Button,
  Space,
  Tag,
  Modal,
  Form,
  Input,
  InputNumber,
  Select,
  Image,
  message,
  Popconfirm,
  Switch,
  Row,
  Col,
  Card,
  List,
  Descriptions
} from 'antd';
import {
  PlusOutlined,
  EditOutlined,
  DeleteOutlined,
  SearchOutlined,
  EyeOutlined,
  LinkOutlined
} from '@ant-design/icons';
import { productAPI, categoryAPI } from '../../services/api';
import { useAdminAuth } from '../../hooks/useAuth';

const { TextArea } = Input;
const { Option } = Select;

const AdminProducts = () => {
  const [loading, setLoading] = useState(false);
  const [products, setProducts] = useState([]);
  const [categories, setCategories] = useState([]);
  const [pagination, setPagination] = useState({
    current: 1,
    pageSize: 10,
    total: 0
  });
  const [searchForm] = Form.useForm();
  const [productForm] = Form.useForm();
  const [modalVisible, setModalVisible] = useState(false);
  const [viewModalVisible, setViewModalVisible] = useState(false);
  const [editingProduct, setEditingProduct] = useState(null);
  const [viewingProduct, setViewingProduct] = useState(null);
  const [imageUrls, setImageUrls] = useState(['']);
  const { hasAdminPermission } = useAdminAuth();  

  // 统一的按钮样式
  const buttonStyle = {
    height: '32px',
    fontSize: '14px',
    fontWeight: '400',
    borderRadius: '6px'
  };

  useEffect(() => {
    loadProducts();
    loadCategories();
  }, []);

  const loadProducts = async (params = {}) => {
    setLoading(true);
    try {
      const response = await productAPI.getAdminProducts({
        page: pagination.current,
        pageSize: pagination.pageSize,
        includeInactive: true, // 后台显示所有状态的商品
        ...params
      });
      
      if (response.success) {
        setProducts(response.data.list);
        setPagination(prev => ({
          ...prev,
          total: response.data.total
        }));
      }
    } catch (error) {
      message.error('加载商品列表失败');
    } finally {
      setLoading(false);
    }
  };

  const loadCategories = async () => {
    try {
      const response = await categoryAPI.getCategories();
      if (response.success) {
        setCategories(response.data);
      }
    } catch (error) {
      console.error('加载分类失败:', error);
    }
  };

  const handleSearch = () => {
    const values = searchForm.getFieldsValue();
    setPagination(prev => ({ ...prev, current: 1 }));
    loadProducts(values);
  };

  const handleReset = () => {
    searchForm.resetFields();
    setPagination(prev => ({ ...prev, current: 1 }));
    loadProducts();
  };

  const handleAdd = () => {
    setEditingProduct(null);
    productForm.resetFields();
    setImageUrls(['']);
    setModalVisible(true);
  };

  const handleEdit = (record) => {
    setEditingProduct(record);
    productForm.setFieldsValue({
      ...record,
      categoryId: record.categoryId?.toString()
    });
    setImageUrls(record.images || ['']);
    setModalVisible(true);
  };

  // 修复查看功能
  const handleView = (record) => {
    setViewingProduct(record);
    setViewModalVisible(true);
  };

  const handleDelete = async (id) => {
    try {
      const response = await productAPI.deleteProduct(id);
      if (response.success) {
        message.success('删除成功');
        loadProducts();
      } else {
        message.error(response.message);
      }
    } catch (error) {
      message.error('删除失败');
    }
  };

  const handleStatusChange = async (id, status) => {
    try {
      const response = await productAPI.updateProduct(id, { status });
      if (response.success) {
        message.success(status === 'active' ? '上架成功' : '下架成功');
        loadProducts();
      } else {
        message.error(response.message);
      }
    } catch (error) {
      message.error('操作失败');
    }
  };

  const handleSubmit = async () => {
    try {
      const values = await productForm.validateFields();
      
      // 处理图片URL
      const validImageUrls = imageUrls.filter(url => url && url.trim());
      if (validImageUrls.length === 0) {
        validImageUrls.push('https://via.placeholder.com/300x300?text=商品图片');
      }
      
      values.images = validImageUrls;
      values.categoryId = parseInt(values.categoryId);

      let response;
      if (editingProduct) {
        response = await productAPI.updateProduct(editingProduct.id, values);
      } else {
        response = await productAPI.addProduct(values);
      }

      if (response.success) {
        message.success(editingProduct ? '更新成功' : '添加成功');
        setModalVisible(false);
        loadProducts();
      } else {
        message.error(response.message);
      }
    } catch (error) {
      message.error('操作失败');
    }
  };

  const handleImageUrlChange = (index, value) => {
    const newUrls = [...imageUrls];
    newUrls[index] = value;
    setImageUrls(newUrls);
  };

  const addImageUrl = () => {
    if (imageUrls.length < 5) {
      setImageUrls([...imageUrls, '']);
    }
  };

  const removeImageUrl = (index) => {
    if (imageUrls.length > 1) {
      const newUrls = imageUrls.filter((_, i) => i !== index);
      setImageUrls(newUrls);
    }
  };

  const columns = [
    {
      title: '商品图片',
      dataIndex: 'images',
      key: 'images',
      width: 100,
      render: (images) => (
        <Image
          width={60}
          height={60}
          src={images?.[0] || 'https://via.placeholder.com/60x60'}
          style={{ objectFit: 'cover', borderRadius: 4 }}
        />
      ),
    },
    {
      title: '商品名称',
      dataIndex: 'name',
      key: 'name',
      ellipsis: true,
      width: 200,
    },
    {
      title: '分类',
      dataIndex: 'categoryId',
      key: 'categoryId',
      render: (categoryId) => {
        const category = categories.find(c => c.id === categoryId);
        return category?.name || '-';
      },
      width: 150,
    },
    {
      title: '价格',
      dataIndex: 'price',
      key: 'price',
      render: (price) => `¥${price?.toFixed(2) || '0.00'}`,
      sorter: true,
      width: 200,
    },
    {
      title: '库存',
      dataIndex: 'stock',
      key: 'stock',
      sorter: true,
      width: 150,
    },
    {
      title: '销量',
      dataIndex: 'sales',
      key: 'sales',
      render: (sales) => sales || 0,
      sorter: true,
      width: 150,
    },
    {
      title: '状态',
      dataIndex: 'status',
      key: 'status',
      render: (status) => (
        <Tag color={status === 'active' ? 'green' : 'red'}>
          {status === 'active' ? '上架' : '下架'}
        </Tag>
      ),
      width: 150,
    },
    {
      title: '操作',
      key: 'action',
      fixed: 'right',
      render: (_, record) => (
        <Space size="small">
          <Button
            type="link"
            icon={<EyeOutlined />}
            size="small"
            style={buttonStyle}
            onClick={() => handleView(record)}
          >
            查看
          </Button>
          
          {hasAdminPermission('product:edit') && (
            <Button
              type="link"
              icon={<EditOutlined />}
              size="small"
              style={buttonStyle}
              onClick={() => handleEdit(record)}
            >
              编辑
            </Button>
          )}
          
          {hasAdminPermission('product:publish') && (
            <Switch
              size="small"
              checked={record.status === 'active'}
              onChange={(checked) => 
                handleStatusChange(record.id, checked ? 'active' : 'inactive')
              }
            />
          )}
          
          {hasAdminPermission('product:delete') && (
            <Popconfirm
              title="确定要删除这个商品吗？"
              onConfirm={() => handleDelete(record.id)}
            >
              <Button
                type="link"
                danger
                icon={<DeleteOutlined />}
                size="small"
                style={buttonStyle}
              >
                删除
              </Button>
            </Popconfirm>
          )}
        </Space>
      ),
    },
  ];

  return (
    <div>
      <Card style={{ marginBottom: 16 }}>
        <Form
          form={searchForm}
          layout="horizontal"
          onFinish={handleSearch}
        >
          <Row gutter={16}>
            <Col span={6}>
              <Form.Item name="keyword" label="关键词">
                <Input placeholder="搜索商品名称" />
              </Form.Item>
            </Col>
            <Col span={6}>
              <Form.Item name="categoryId" label="分类">
                <Select placeholder="选择分类" allowClear>
                  {categories.map(category => (
                    <Option key={category.id} value={category.id}>
                      {category.name}
                    </Option>
                  ))}
                </Select>
              </Form.Item>
            </Col>
            <Col span={6}>
              <Form.Item name="status" label="状态">
                <Select placeholder="选择状态" allowClear>
                  <Option value="active">上架</Option>
                  <Option value="inactive">下架</Option>
                </Select>
              </Form.Item>
            </Col>
            <Col span={6}>
              <Space>
                <Button 
                  type="primary" 
                  htmlType="submit" 
                  icon={<SearchOutlined />}
                  style={buttonStyle}
                >
                  搜索
                </Button>
                <Button onClick={handleReset} style={buttonStyle}>重置</Button>
              </Space>
            </Col>
          </Row>
        </Form>
      </Card>

      <Card
        title="商品管理"
        extra={
          hasAdminPermission('product:add') && (
            <Button
              type="primary"
              icon={<PlusOutlined />}
              onClick={handleAdd}
              style={buttonStyle}
            >
              添加商品
            </Button>
          )
        }
      >
        <Table
          columns={columns}
          dataSource={products}
          rowKey="id"
          loading={loading}
          pagination={{
            ...pagination,
            showSizeChanger: true,
            showQuickJumper: true,
            showTotal: (total) => `共 ${total} 条记录`,
            onChange: (page, pageSize) => {
              setPagination(prev => ({ ...prev, current: page, pageSize }));
              loadProducts({ page, pageSize });
            },
          }}
          scroll={{ x: 1200 }}
        />
      </Card>

      {/* 商品查看模态框 */}
      <Modal
        title="商品详情"
        open={viewModalVisible}
        onCancel={() => setViewModalVisible(false)}
        footer={[
          <Button key="close" onClick={() => setViewModalVisible(false)} style={buttonStyle}>
            关闭
          </Button>
        ]}
        width={800}
      >
        {viewingProduct && (
          <div>
            <Descriptions bordered column={2}>
              <Descriptions.Item label="商品名称">{viewingProduct.name}</Descriptions.Item>
              <Descriptions.Item label="商品分类">
                {categories.find(c => c.id === viewingProduct.categoryId)?.name || '-'}
              </Descriptions.Item>
              <Descriptions.Item label="商品价格">¥{viewingProduct.price?.toFixed(2)}</Descriptions.Item>
              <Descriptions.Item label="原价">
                {viewingProduct.originalPrice ? `¥${viewingProduct.originalPrice.toFixed(2)}` : '-'}
              </Descriptions.Item>
              <Descriptions.Item label="库存数量">{viewingProduct.stock}</Descriptions.Item>
              <Descriptions.Item label="销量">{viewingProduct.sales || 0}</Descriptions.Item>
              <Descriptions.Item label="浏览量">{viewingProduct.views || 0}</Descriptions.Item>
              <Descriptions.Item label="商品状态">
                <Tag color={viewingProduct.status === 'active' ? 'green' : 'red'}>
                  {viewingProduct.status === 'active' ? '上架' : '下架'}
                </Tag>
              </Descriptions.Item>
              <Descriptions.Item label="创建时间" span={2}>
                {viewingProduct.createTime ? new Date(viewingProduct.createTime).toLocaleString() : '-'}
              </Descriptions.Item>
              <Descriptions.Item label="商品描述" span={2}>
                {viewingProduct.description || '-'}
              </Descriptions.Item>
            </Descriptions>
            
            {viewingProduct.images && viewingProduct.images.length > 0 && (
              <>
                <h4 style={{ marginTop: 16, marginBottom: 8 }}>商品图片</h4>
                <Space>
                  {viewingProduct.images.map((img, index) => (
                    <Image
                      key={index}
                      width={100}
                      height={100}
                      src={img}
                      style={{ borderRadius: 4 }}
                    />
                  ))}
                </Space>
              </>
            )}
          </div>
        )}
      </Modal>

      {/* 添加/编辑商品模态框 */}
      <Modal
        title={editingProduct ? '编辑商品' : '添加商品'}
        open={modalVisible}
        onOk={handleSubmit}
        onCancel={() => setModalVisible(false)}
        width={800}
        destroyOnClose
        okButtonProps={{ style: buttonStyle }}
        cancelButtonProps={{ style: buttonStyle }}
      >
        <Form
          form={productForm}
          layout="vertical"
          initialValues={{
            status: 'active',
            stock: 0,
            sales: 0
          }}
        >
          <Row gutter={16}>
            <Col span={12}>
              <Form.Item
                name="name"
                label="商品名称"
                rules={[{ required: true, message: '请输入商品名称' }]}
              >
                <Input placeholder="请输入商品名称" />
              </Form.Item>
            </Col>
            <Col span={12}>
              <Form.Item
                name="categoryId"
                label="商品分类"
                rules={[{ required: true, message: '请选择商品分类' }]}
              >
                <Select placeholder="请选择商品分类">
                  {categories.map(category => (
                    <Option key={category.id} value={category.id.toString()}>
                      {category.name}
                    </Option>
                  ))}
                </Select>
              </Form.Item>
            </Col>
          </Row>

          <Row gutter={16}>
            <Col span={8}>
              <Form.Item
                name="price"
                label="商品价格"
                rules={[{ required: true, message: '请输入商品价格' }]}
              >
                <InputNumber
                  min={0}
                  precision={2}
                  style={{ width: '100%' }}
                  placeholder="0.00"
                />
              </Form.Item>
            </Col>
            <Col span={8}>
              <Form.Item
                name="originalPrice"
                label="原价"
              >
                <InputNumber
                  min={0}
                  precision={2}
                  style={{ width: '100%' }}
                  placeholder="0.00"
                />
              </Form.Item>
            </Col>
            <Col span={8}>
              <Form.Item
                name="stock"
                label="库存数量"
                rules={[{ required: true, message: '请输入库存数量' }]}
              >
                <InputNumber
                  min={0}
                  style={{ width: '100%' }}
                  placeholder="0"
                />
              </Form.Item>
            </Col>
          </Row>

          <Form.Item
            name="description"
            label="商品描述"
          >
            <TextArea
              rows={4}
              placeholder="请输入商品描述"
            />
          </Form.Item>

          <Form.Item label="商品图片">
            <div style={{ marginBottom: '16px' }}>
              <Button 
                type="dashed" 
                icon={<PlusOutlined />} 
                onClick={addImageUrl}
                disabled={imageUrls.length >= 5}
                style={buttonStyle}
              >
                添加图片URL ({imageUrls.length}/5)
              </Button>
            </div>
            <List
              dataSource={imageUrls}
              renderItem={(url, index) => (
                <List.Item
                  actions={imageUrls.length > 1 ? [
                    <Button 
                      type="link" 
                      danger 
                      size="small"
                      onClick={() => removeImageUrl(index)}
                      style={buttonStyle}
                    >
                      删除
                    </Button>
                  ] : []}
                >
                  <Input
                    placeholder="请输入图片URL地址"
                    value={url}
                    onChange={(e) => handleImageUrlChange(index, e.target.value)}
                    prefix={<LinkOutlined />}
                    style={{ width: '100%' }}
                  />
                </List.Item>
              )}
            />
            <div style={{ marginTop: '8px', color: '#666', fontSize: '12px' }}>
              支持输入图片URL地址，最多5张图片
            </div>
          </Form.Item>

          <Form.Item
            name="status"
            label="商品状态"
          >
            <Select>
              <Option value="active">上架</Option>
              <Option value="inactive">下架</Option>
            </Select>
          </Form.Item>
        </Form>
      </Modal>
    </div>
  );
};

export default AdminProducts;